package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.web.page.PageDomain;
import com.spzx.common.core.web.page.TableSupport;
import com.spzx.product.domain.ProductSpec;
import com.spzx.product.mapper.ProductSpecMapper;
import com.spzx.product.service.ProductSpecService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpec>
        implements ProductSpecService {
    @Override
    public Page<ProductSpec> listPage(ProductSpec productSpec) {
        //使用mp自定义分页查询的sql
        //mp的Mapper方法如果传入了page对象，并且配置了分页拦截器  会自动使用分页条件

        //1、将分页条件封装为分页对象
        PageDomain pageDomain = TableSupport.getPageDomain();
        Page<ProductSpec> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());

        //2、自定义mapper方法分页查询
        //2.1、构建查询条件
        QueryWrapper<ProductSpec> wrapper = Wrappers.query();
        String specName = productSpec.getSpecName();
        Long categoryId = productSpec.getCategoryId();
        if(categoryId != null){
            query().eq("category_id", categoryId);
        }
        if(StringUtils.isNotEmpty(specName)){
            query().like("spec_name", specName);
        }
        wrapper.eq("t1.del_flag", "0");
        //2.2、调用自定义sql 传入分页 查询条件对象
        List<ProductSpec> list = baseMapper.selectProductSpecPage(page, wrapper);
        page.setRecords(list);
        return page;
    }

    @Override
    public void checkProductSpecUnique(ProductSpec productSpec) {
        long id = productSpec.getId() == null ? -1L : productSpec.getId();
        ProductSpec spec = baseMapper.selectOne(Wrappers.lambdaQuery(ProductSpec.class)
                .eq(ProductSpec::getSpecName, productSpec.getSpecName())
                .eq(ProductSpec::getCategoryId, productSpec.getCategoryId())
                .last("limit 1"));
        if(spec != null && spec.getId().longValue() != id){
            throw new RuntimeException("规格名称已存在");
        }
    }
}
